package com.ruoyi.framework.handler;


import com.alibaba.fastjson2.JSON;
import com.mongodb.MongoNamespace;
import com.mongoplus.enums.ExecuteMethodEnum;
import com.mongoplus.handlers.CollectionNameHandler;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.BsonString;
import org.bson.conversions.Bson;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CustomCollectionNameHandler implements CollectionNameHandler {
    @Override
    public String dynamicCollectionName(ExecuteMethodEnum executeMethodEnum, Object[] source, MongoNamespace namespace) {

        if (executeMethodEnum == ExecuteMethodEnum.QUERY && namespace.getCollectionName().equals("pointvalue")){
            // 具体类型参数转换参考com.anwen.mongo.execute.Execute接口，
            // 比如查询(executeQuery(Bson, BasicDBObject, BasicDBObject, Class<T>, MongoCollection<Document>))，
            // 对应的第0个参数类型为Bson
            Bson bson = (Bson) source[0];
            BsonInt64 deviceId = bson.toBsonDocument().getDocument("deviceId").getInt64("$eq",null);
            // 如果userName == 张三
            if (StringUtils.isNotNull(deviceId.getValue())) {
                //返回新集合名为：user_zhangsan
                return "point_value_"+deviceId.getValue();
            }
        }
        //条件不满足则返回原名称
        return namespace.getCollectionName();
    }
}